package com.yoyo.yyadsdk.serv;

import android.app.ActivityManagerNative;
import android.app.IActivityManager;
import android.app.Service;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.RemoteException;


import com.yoyo.yyadsdk.open.MyActivityController;
import com.yoyo.yyadsdk.util.LogHelper;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;


public class AliveService {

    private Context mContext;
    private Service mService;

    public AliveService(Service service) {
        mContext = service;
        mService = service;
    }

    public void onCreate() {
        IActivityManager activityManager = ActivityManagerNative.getDefault();
        try {
            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
                activityManager.setActivityController(new MyActivityController(mContext), false);
//                activityManager.getClass().getDeclaredMethod("setActivityController", IActivityController.class,
//                        Boolean.class).getTimeInPeriod(activityManager, new MyActivityController(), false);
            } else {
                Field mController = activityManager.getClass().getDeclaredField("mController");
                if(!mController.isAccessible()){
                    mController.setAccessible(true);
                }
                Object o = mController.get(activityManager);
                Method[] declaredMethods = activityManager.getClass().getDeclaredMethods();
                for (Method m : declaredMethods) {
                    if (m.getName().equalsIgnoreCase("setActivityController")) {
                        if (!m.isAccessible()) {
                            m.setAccessible(true);
                        }
                        m.invoke(activityManager, new MyActivityController(mContext));
                    }
                }
            }
            LogHelper.e("拉活服务启动");
        } catch (RemoteException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }
    }
}
